package com.neutech.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(urlPatterns = "/*")
public class AuthServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        String path = request.getPathInfo();

        request.setCharacterEncoding("utf-8");

        response.setContentType("text/html;charset=utf-8");

        response.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if ("/login".equals(path)) {
            if ("user".equals(username) && "pass".equals(password)) {
                HttpSession session = request.getSession();
                session.setAttribute("user", username);
                response.getWriter().println("登录成功. Session ID: " +
                        session.getId());
            } else {
                response.getWriter().println("无效的凭据.");
            }
        } else if ("/logout".equals(path)) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
                response.getWriter().println("退出登录.");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse
            response) throws ServletException, IOException {
        String path = request.getPathInfo();
//设置请求信息的字符编码（必须在使用request之前进行设置）
        request.setCharacterEncoding("utf-8");
//使客户端浏览器并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
        response.setContentType("text/html;charset=utf-8");
//设置响应信息的字符编码（必须在创建响应输出流之前进行设置）
        response.setCharacterEncoding("utf-8");
        if ("/checkStatus".equals(path)) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                response.getWriter().println("用户已经登录. Session ID: " +
                        session.getId());
            } else {
                response.getWriter().println("用户未登录.");
            }

        }
    }
}
